require 'daemons'
require File.expand_path(File.join(File.dirname(__FILE__), '..', 'config', 'environment'))

Daemons.run_proc('mydaemon', :backtrace => true) do
  logger = ActiveSupport::BufferedLogger.new(
    File.join(Rails.root, "log", "mydaemon.log"),Logger::INFO)
  Rails.logger = logger
  ActiveRecord::Base.logger = logger
  ilms = SerialInterface.new
  s = UtilityFunctions.current_interval/2
  
  loop do
    sleep(5)
    outlets = OutletStatus.get_outlet_status
    user = UserSetting.get_user_settings
    green = 300.0 #GreenSimulation.get_green_power
    power = PowerLog.get_power_consumption
    utility  = UtilitySetting.last
	checked = PowerLog.find(:all, :order => "id desc", :limit => 5)
	 
	sum = 0
	checked.each do |check|
   		sum = sum + check.power_consumption
   	end
	avg = sum/5
	if avg == 0
		avg = 1
	end

	avg_percent = green / avg
    data = AlgorithmProcessor.run_algorithmPastFive(outlets, user, green, power, utility, avg_percent)
    ilms.send_outlet(data)
    logger.info "#{user.consumption_preference}, #{utility.override_lvl}, #{avg_percent}, #{green}, #{outlets[4].user_override}"
  end
end
